package com.grandtech.insurance.common.compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public final class GZip {

    public static byte[] compress(byte[] data) {
        if (data == null) return null;
        byte[] ret = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(bos);
            gzip.write(data);
            gzip.finish();
            gzip.close();
            ret = bos.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ret;
        }
    }


    public static byte[] unCompress(byte[] data) {
        if (data == null) return null;
        byte[] ret = null;
        ByteArrayInputStream bis = null;
        ByteArrayOutputStream bos = null;
        GZIPInputStream gzip = null;
        try {
            bis = new ByteArrayInputStream(data);
            gzip = new GZIPInputStream(bis);
            byte[] buf = new byte[1024];
            int num = -1;
            bos = new ByteArrayOutputStream();
            while ((num = gzip.read(buf, 0, buf.length)) != -1) {
                bos.write(buf, 0, num);
            }
            ret = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                gzip.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                bos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ret;
        }
    }
}
